import axios from 'axios';
import store from '@/store';
import { getToken } from '@/utils/auth';
import * as code from '@/config/code';
import { Toast } from 'vant';

const service = axios.create({
  baseURL: '/',
  timeout: 5000
});

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['user-token'] = getToken();
  }
  return config;
}, error => {
  Promise.reject(error);
});

export default function request (options) {
  return new Promise((resolve, reject) => {
    service(options)
      .then(({ data }) => {
        if (~code.SUCCESS.indexOf(data.code)) {
          resolve(data);
        } else if (~code.NOT_LOGIN.indexOf(data.code)) {
          Toast('登录失效，请稍后重新登录');
        } else {
          // 在出口进行消息提示，而不用去处理每个子接口的消息提示和异常打印
          Toast(data.message);
          reject(data);
        }
      })
      .catch((error) => {
        console.error(error);
        reject(error);
      });
  });
}
